<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import * as echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    lineName: {
      type: String,
      default: 'lineChart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartData: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler() {
        this.initChart()
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      if (this.chartData.length <= 0) return
      this.chart = echarts.init(this.$el, 'macarons')
      const dateList = this.chartData[0].list.map(val => {
        return val[0]
      })

      const legendList = this.chartData.map(val => {
        return val.name
      })

      const seriesList = this.chartData.map(val => {
        return {
          name: val.name,
          type: 'line',
          stack: 'Total',
          data: val.list.map(value => {
            return value[1]
          })
        }
      })
      this.setOptions(this.lineName, seriesList, dateList, legendList)
    },
    setOptions(lineName, seriesList, dateList, legendList) {
      this.chart.setOption({
        title: {
          text: lineName,
          left: '10px'
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: '#fff'
        },
        legend: {
          right: '20px',
          data: legendList
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dateList
        },
        yAxis: {
          type: 'value'
        },
        series: seriesList
      })
    }
  }
}
</script>
